package com.api.oauthservices.getaccesstoken;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.api.client.impl.OAuthProvider;
import com.api.test.OAuthServiceConfig;

public class GetAccessToken {

	private static final ApplicationContext API_CONTEXT = new ClassPathXmlApplicationContext("classpath*:/api-context.xml");

	private final OAuthServiceConfig oauthConfig = API_CONTEXT.getBean(OAuthServiceConfig.class);

	private String username = "qazyncro@gmail.com";
	private String password = "123456";

	@Test
	public void testWithoutParameters() {
		OAuthRequest request = new OAuthRequest(Verb.POST, oauthConfig.getAccessEndpoint());

		Response response = request.send();

		Assert.assertFalse(response.getCode() >= 200 && response.getCode() < 300);
	}

	@Test
	public void test() {

		OAuthRequest request = new OAuthRequest(Verb.POST, oauthConfig.getAuthorizationEndpoint());

		OAuthProvider provider = new OAuthProvider(oauthConfig);
		Token requestToken = provider.getService().getRequestToken();

		request.addBodyParameter("username", username);
		request.addBodyParameter("password", password);
		request.addBodyParameter("request_token", requestToken.getToken());

		request.send();

		Token accessToken = provider.getService().getAccessToken(requestToken, new Verifier(""));

		System.out.println(accessToken);

		Assert.assertNotNull(accessToken);
	}
}
